import { debug } from '@/common'
// import { useSystemStore } from '@/store/system/index'
import { errUpload } from './upload-api.js'

class BaseUploadInfo {
  constructor(type) {
    const uploadTime = +new Date()
    this.eventType = type
    this.uploadTime = uploadTime
    this.pagePath = uni.$PAGE_PATH
  }
}

class AppErrUploadInfo extends BaseUploadInfo {
  constructor(err) {
    super('appErr')
    this.clientInfo = JSON.stringify(getDeviceInfo())
    this.message = JSON.stringify(err)
  }
}

class ReqErrUploadInfo extends BaseUploadInfo {
  constructor(err = {}) {
    super('reqErr')
    this.clientInfo = JSON.stringify(getDeviceInfo())
    const { statusCode, config, data } = err
    this.message = JSON.stringify({
      statusCode,
      config,
      data
    })
  }
}

class ImgErrUploadInfo extends BaseUploadInfo {
  constructor(err) {
    super('imgErr')
    this.message = JSON.stringify(err)
  }
}

class VisitUploadInfo extends BaseUploadInfo {
  constructor(visitInfo) {
    super('pageVisit')
    this.message = JSON.stringify(visitInfo)
  }
}

export function imgErrHandler(e) {
  // 图片错误事件上报
  errAndLogUpload(new ImgErrUploadInfo(e))
}

export function reqErrHandler(e) {
  // 请求错误事件上报
  errAndLogUpload(new ReqErrUploadInfo(e))
}

export function appErrHandler(e) {
  // APP内部错误事件上报
  errAndLogUpload(new AppErrUploadInfo(e))
}

export function pageStatistics(e) {
  // 用户页面访问路径，停留时长统计
  errAndLogUpload(new VisitUploadInfo(e))
}

function errAndLogUpload(logObj) {
  // console.log(logObj)
  if (debug) return
  errUpload(logObj)
  // setTimeout(() => {
  //   let img = new Image()
  //   img.src = 'http://www.baidu.com?err=' + JSON.stringify(e)
  // })
}

let deviceInfo = null
export function getDeviceInfo(reset) {
  if (reset) deviceInfo = null
  if (deviceInfo) return deviceInfo
  deviceInfo = uni.getSystemInfoSync()
  return deviceInfo
}
